<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="省" prop="provinceName">
        <el-input
          v-model="queryParams.provinceName"
          placeholder="请输入省名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="市" prop="cityName">
        <el-input
          v-model="queryParams.cityName"
          placeholder="请输入市名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="区/县" prop="countyName">
        <el-input
          v-model="queryParams.countyName"
          placeholder="请输入区/县名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="省编码" prop="province">-->
<!--        <el-input-->
<!--          v-model="queryParams.province"-->
<!--          placeholder="请输入省编码"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="市编码" prop="city">-->
<!--        <el-input-->
<!--          v-model="queryParams.city"-->
<!--          placeholder="请输入市编码"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="区/县编码" prop="county">-->
<!--        <el-input-->
<!--          v-model="queryParams.county"-->
<!--          placeholder="请输入区/县编码"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="行政区域编码" prop="regionCode">-->
<!--        <el-input-->
<!--          v-model="queryParams.regionCode"-->
<!--          placeholder="请输入行政区域编码"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="行政区域" prop="regionName">-->
<!--        <el-input-->
<!--          v-model="queryParams.regionName"-->
<!--          placeholder="请输入行政区域名称"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item>
	    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['shop:postage:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="postageList"
      row-key="id"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="运费生效范围" align="center" prop="regionName" />
      <el-table-column label="省" align="center" prop="provinceName" />
      <el-table-column label="市" align="center" prop="cityName" />
      <el-table-column label="区/县" align="center" prop="countyName" />
      <el-table-column label="运费（元）" align="center" prop="cost" >
        <template v-slot="scope">
          <span>{{(scope.row.cost / 100).toFixed(2)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template v-slot="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['shop:postage:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['shop:postage:add']"
          >新增</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['shop:postage:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改邮费配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-col :span="22">
          <el-form-item label="父级配置" prop="parentId">
            <treeselect v-model="form.parentId" :options="postageOptions" :normalizer="normalizer" placeholder="请选择父级id" />
          </el-form-item>
        </el-col>
        <el-col :span="22">
          <el-form-item label="地址选择" prop="regionCode">
            <el-cascader
              placeholder="请选择地址"
              v-model="areaEditSelects"
              :options="areaOptions"
              :props="areaProps"
              filterable
              style="width: 100%;"
            ></el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="22">
          <el-form-item label="省" prop="provinceName">
            <el-input v-model="form.provinceName" placeholder="请输入省名称" disabled/>
          </el-form-item>
        </el-col>
        <el-col :span="22">
          <el-form-item label="市" prop="provinceName">
            <el-input v-model="form.cityName" placeholder="请输入市名称" disabled/>
          </el-form-item>
        </el-col>
        <el-col :span="22">
          <el-form-item label="区/县" prop="provinceName">
            <el-input v-model="form.countyName" placeholder="请输入区/县名称" disabled/>
          </el-form-item>
        </el-col>
        <el-col :span="22">
<!--        <el-form-item label="省编码" prop="province">-->
<!--          <el-input v-model="form.province" placeholder="请输入省编码" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="市编码" prop="city">-->
<!--          <el-input v-model="form.city" placeholder="请输入市编码" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="区/县编码" prop="county">-->
<!--          <el-input v-model="form.county" placeholder="请输入区/县编码" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="行政区域编码" prop="regionCode">-->
<!--          <el-input v-model="form.regionCode" placeholder="请输入行政区域编码" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="行政区域名称" prop="regionName">-->
<!--          <el-input v-model="form.regionName" placeholder="请输入行政区域名称" />-->
<!--        </el-form-item>-->
        </el-col>
        <el-col :span="22">
          <el-form-item label="费用（元）" prop="cost">
            <el-input-number style="width: 100%;" v-model="form.cost" placeholder="请输入费用" controls-position="right" :step="1" :precision="2"/>
          </el-form-item>
        </el-col>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPostage, getPostage, delPostage, addPostage, updatePostage } from "@/api/shop/postage";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {listArea} from "@/api/baseplatform/area";
import {handleRegionCascader} from "@/api/shop/goodsCenters";

export default {
  name: "Postage",
  components: {
    Treeselect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 邮费配置表格数据
      postageList: [],
      // 邮费配置树选项
      postageOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        parentId: null,
        provinceName: null,
        cityName: null,
        countyName: null,
        province: null,
        city: null,
        county: null,
        regionCode: null,
        regionName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        provinceName: [
          { required: true, message: "请进行地址选择", trigger: "blur" }
        ],
        cost: [
          { required: true, message: "费用不能为空", trigger: "blur" }
        ],
      },
      // 区域地址编辑框选中项
      areaEditSelects: [],
      // 区域地址数据源
      areaOptions: [],
      //
      areaProps: {
        checkStrictly: true,
        lazy: true,
        lazyLoad (node, resolve) {
          let nodes = [];
          if (node.level > 0) {
            const params = {pAreaCode: node.value}
            listArea(params).then(res => {
              nodes = handleRegionCascader(res.data, 'areaCode', 'areaName', 'pAreaCode');
              resolve(nodes);
            });
          }
        }
      },
    };
  },
  created() {
    this.getList();
    this.getAreaList({areaLevel: '1'});
  },
  methods: {
    /** 查询邮费配置列表 */
    getList() {
      this.loading = true;
      listPostage(this.queryParams).then(response => {
        this.postageList = this.handleTree(response.data, "id", "parentId");
        this.loading = false;
      });
    },
    getAreaList(params) {
      listArea(params).then(res => {
        this.areaOptions = handleRegionCascader(res.data, 'areaCode', 'areaName', 'pAreaCode');
      });
    },
    /** 转换邮费配置数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.regionName,
        children: node.children
      };
    },
	/** 查询邮费配置下拉树结构 */
    getTreeselect() {
      listPostage().then(response => {
        this.postageOptions = [];
        const data = { id: 0, regionName: '顶级节点', children: [] };
        data.children = this.handleTree(response.data, "id", "parentId");
        this.postageOptions.push(data);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        parentId: null,
        provinceName: null,
        cityName: null,
        countyName: null,
        province: null,
        city: null,
        county: null,
        regionCode: null,
        regionName: null,
        cost: null,
        isDel: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.getTreeselect();
      if (row != null && row.id) {
        this.form.parentId = row.id;
      } else {
        this.form.parentId = 0;
      }
      this.open = true;
      this.title = "添加邮费配置";
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      if (row != null) {
        this.form.parentId = row.id;
      }
      getPostage(row.id).then(response => {
        this.form = response.data;
        this.form.cost /= 100;
        this.open = true;
        this.title = "修改邮费配置";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePostage(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPostage(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.form.cost /= 100;
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除【' + row.regionName + '】的邮费配置？').then(function() {
        return delPostage(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    }
  },
  watch: {
    areaEditSelects(val) {
      const data = JSON.parse(localStorage.getItem("REGION_MAP"));
      this.form.regionCode = val[val.length - 1];
      this.form.regionName = data[val[val.length - 1]];
      if (val.length === 3) {
        this.form.province = val[0];
        this.form.provinceName = data[val[0]];
        this.form.city = val[1];
        this.form.cityName = data[val[1]];
        this.form.county = val[2];
        this.form.countyName = data[val[2]];
      } else if (val.length === 2) {
        this.form.province = val[0];
        this.form.provinceName = data[val[0]];
        this.form.city = val[1];
        this.form.cityName = data[val[1]];
        this.form.county = null;
        this.form.countyName = null;
      } else if (val.length === 1) {
        this.form.province = val[0];
        this.form.provinceName = data[val[0]];
        this.form.city = null;
        this.form.cityName = null;
        this.form.county = null;
        this.form.countyName = null;
      }
    }
  }
};
</script>
